﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;
using Controller.Enum;
using Controller.Helper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Model;


namespace SalePriceSystem.Page
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class Handler1 : IHttpHandler,System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string ADAuthen = HttpContext.Current.User.Identity.Name;
            string ip = HttpContext.Current.Request.UserHostAddress;
            //if (HttpContext.Current.Session != null && HttpContext.Current.Session["ip"] != null && HttpContext.Current.Session["ip"].ToString() != ip)
            //{
            //    const string complete = "{'Error':" + "'-0'}";
            //    context.Response.ContentType = "text/plain";
            //    context.Response.Write(JObject.Parse(complete));
            //    context.Response.End();
            //}
            //else
            //{
            //    HttpContext.Current.Session["ip"] = ip;
            //}
            //if (String.IsNullOrEmpty(Controller.AD.LdapAuthentication.GetCurrentUserRole()))
            //{
                
            //    string domain = WebConfigurationManager.AppSettings["ADDomainName"] ?? "KCUS";
            //    domain = domain + "\\";
            //    if (!String.IsNullOrEmpty(ADAuthen))
            //    {
            //        ADAuthen = ADAuthen.Replace(domain, "");
            //        tblUser currentUser = new tblUser();
            //        List<tblUser> u = Controller.Helper.Member.GetUserDB(ADAuthen);
            //        if (u.Count > 0)
            //        {
            //            currentUser = u[0];
            //            Controller.AD.LdapAuthentication.SetAuthen(currentUser);
            //        }
            //        else
            //        {
            //            const string complete = "{'Error':" + "'-0'}";
            //            context.Response.ContentType = "text/plain";
            //            context.Response.Write(JObject.Parse(complete));
            //            context.Response.End();
            //        }
            //    }
            //    else
            //    {
            //        const string complete = "{'Error':" + "'-0'}";
            //        context.Response.ContentType = "text/plain";
            //        context.Response.Write(JObject.Parse(complete));
            //        context.Response.End();
            //    }
            //}

            string Medthod = post["metdhodName"];
            switch (Medthod.Trim())
            {
                case "UpdateRoleDB":
                    UpdateRole(context);
                    break;
                case "GetLastestNDPrice":
                    GetNdPrice(context);
                    break;
                case "GetUserDB":
                    string kk = Controller.Helper.Member.GetUserDBjson();
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(kk);
                    break;
                case "GetStatusTab":
                    GetStatusTab(context);

                    break;
                case "GetDocumentByUser":
                    GetDocumentByUser(context);

                    break;
                case "GetDocumentDetailByDocID":
                    GetDocumentDetailByDocID(context);

                    break;
                case "GetColumnDocumentDetailByDocID":
                    GetColumnDocumentDetailByDocID(context);
                    break;
                case "GetCustomerBySaleAndDC":
                    GetCustomerBySaleAndDC(context);
                    break;
                case "GetCustomerBySaleAllDc":
                    GetCustomerBySaleAllDc(context);
                    break;   
                case "GetProductToSale":
                    GetProductToSale(context);
                    break;
                case "GetAllSale":
                    GetAllSale(context);
                    break;
                case "GetAllSaleCo":
                    GetAllSaleCo(context);
                    break;
                case "GetAllApprover":
                    GetAllApprover(context);
                    break;

                case "GetDocumentByApproveUser":
                    GetDocumentByApproveUser(context);
                    break;

                case "GetDocumentByAdmin":
                    GetDocumentByAdmin(context);
                    break;

                case "GetCurrentUserDetail":
                    GetCurrentUserDetail(context);
                    break;

                case "GetSaleClientBySaleCo":
                    GetSaleClientBySaleCo(context);
                    break;
                case "SetCurrentUserDetail":
                    SetCurrentUserDetail(context);
                    break;
                case "CheckADuser":
                    CheckADuser(context);
                    break;
                case "GetProductCate":
                    GetProductCate(context);
                    break;
                case "GetProductHier":
                    GetProductHier(context);
                    break;
                case "GetAllApproverMapping":
                    GetAllApproverMapping(context);
                    break;
                case "GetAllSaleCoMapping":
                    GetAllSaleCoMapping(context);
                    break;
                case "ExportSaPfile":
                    ExportSaPfile(context);
                    break;
                case "DeleteDocs":
                    DeleteDocs(context);
                    break;
                case "ReNewPincode":
                    ReNewPincode(context);
                    break;
                case "VerifyPincode":
                    VerifyPincode(context);
                    break;
                case "getAllNdPrice":
                    getAllNdPrice(context);
                    break;
                case "getLastestNdPriceItemJson":
                    getLastestNdPriceItemJson(context);
                    break;
                case "GetCustomerListByDocs":
                    GetCustomerListByDocs(context);
                    break; 
                case "ExportSaPNDfile":
                    ExportSaPNDfile(context);
                    break;
                case "GetAllApproveLevel":
                    GetAllApproveLevel(context);
                    break;
                case "SaveAllApproveLevel":
                    SaveAllApproveLevel(context);
                    break;

            }



        }

        public void UpdateRole(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string RoleDatea = post["postData"];
            var roles = JsonConvert.DeserializeObject<List<tblRole>>(RoleDatea);

            HttpContext.Current.Response.Write("");

        }

        public void GetAllApproveLevel(HttpContext context)
        {
            string result = Approver.GetAllApproveLevel();
            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
            context.Response.End();
        }
        public void SaveAllApproveLevel(HttpContext context)
        {
            var d = context.Request["postData[approveData]"];
            var approvals = JsonConvert.DeserializeObject<List<tblApproval>>(d);
            bool result = Approver.SaveAllApproveLevel(approvals);
            context.Response.ContentType = "text/plain";
            context.Response.Write(JsonConvert.SerializeObject(result));
            context.Response.End();
        }
        
        public void GetNdPrice(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string ndround = post["postData[ndround]"];
            string kk = !string.IsNullOrEmpty(ndround) ? Controller.Helper.NDPrice.GetNDPricejson(int.Parse(ndround)) : Controller.Helper.NDPrice.GetNDPricejson();
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);
        }

        public void GetStatusTab(HttpContext context)
        {
            string currentUserRole = Controller.AD.LdapAuthentication.GetCurrentUserRole();
            string kk = Controller.Helper.DocumentStatus.GetStatusByRoleJson(currentUserRole);
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);
        }
        public void GetDocumentByUser(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string sort = post["postData[sort]"];
            string doctype = post["postData[doctype]"];
            string currentUser = Controller.AD.LdapAuthentication.GetCurrentUser();
            if (!string.IsNullOrEmpty(Controller.AD.LdapAuthentication.GetCurrentRepresendto()))
            {
                currentUser = Controller.AD.LdapAuthentication.GetCurrentRepresendto();
            }
            string kk = Controller.Helper.Document.GetDocumentByUser(currentUser, doctype, sort);
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);
        }

        public void GetDocumentDetailByDocID(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string data = post["postData[docID]"];
            string isdraft = post["postData[isdraft]"];
            bool isdraftBool = false;
            if (!string.IsNullOrEmpty(isdraft))
            {
                bool.TryParse(isdraft, out isdraftBool);
            }
            if (string.IsNullOrEmpty(data))
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("");
            }
            else
            {
                string kk = Controller.Helper.Document.GetDocumentDetailByDocID(data.Trim(), isdraftBool);
                context.Response.ContentType = "text/plain";
                context.Response.Write(kk);
            }
        }

        public void GetColumnDocumentDetailByDocID(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string data = post["postData[docID]"];
            string doctype = post["postData[doctype]"];
            if (string.IsNullOrEmpty(data))
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("");
            }
            else
            {
                string kk = Document.GetColumnDocumentDetailByDocID(data.Trim(), doctype.Trim());
                context.Response.ContentType = "text/plain";
                context.Response.Write(kk);
            }
        }

        public void GetCustomerBySaleAndDC(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string dc = post["postData[dc]"];
            string doctype = post["postData[doctype]"];
            string salegrp = Controller.AD.LdapAuthentication.GetCurrentSaleGrp();
            if (string.IsNullOrEmpty(salegrp))
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("");
            }
            else
            {
                string kk = Sale.GetCustomerBySale(dc, salegrp.Trim(), doctype.Trim());
                context.Response.ContentType = "text/plain";
                context.Response.Write(kk);
            }
        }

        public void GetCustomerBySaleAllDc(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string doctype = post["postData[doctype]"];
            string salegrp = Controller.AD.LdapAuthentication.GetCurrentSaleGrp();
            if (string.IsNullOrEmpty(salegrp))
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("");
            }
            else
            {
                string kk = Sale.GetAllDcCustomerBySale(salegrp.Trim(), doctype.Trim());
                context.Response.ContentType = "text/plain";
                context.Response.Write(kk);
            }
        }

        public void GetProductToSale(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            //string dc = post["postData[dc]"];
            string docID = post["postData[docid]"];
            string kk = string.Empty;
            if (string.IsNullOrEmpty(docID))
            {
                kk = Controller.Helper.Product.GetProductToSale();
            }
            else
            {
                kk = Controller.Helper.Product.GetProductToSale(docID);
            }
            
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);
        }

        public void GetAllSale(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;

            string kk = Controller.Helper.Sale.GetAllSale();
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }

        public void GetAllSaleCo(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;

            string kk = Controller.Helper.SaleCo.GetAllSaleCo();
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }
        public void GetAllApprover(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;

            string kk = Controller.Helper.Approver.GetAllApprover();
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }

        public void GetDocumentByAdmin(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;

            string kk = Controller.Helper.Document.GetDocumentByAdmin();
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }



        public void GetDocumentByApproveUser(HttpContext context)
        {

            string role = Controller.AD.LdapAuthentication.GetCurrentUserRole();
            string ApproverRoleName = WebConfigurationManager.AppSettings["ApproverRoleName"] ?? "Approver";
            if (role == ApproverRoleName)
            {
                string userName = Controller.AD.LdapAuthentication.GetCurrentUser();
                if (string.IsNullOrEmpty(userName))
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("");
                }
                else
                {
                    string kk = Controller.Helper.Document.GetDocumentByApproveUser(userName);
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(kk);
                }
            }
            else
            {
                const string complete = "{'Error':" + "'-0'}";
                context.Response.ContentType = "text/plain";
                context.Response.Write(JObject.Parse(complete));
                context.Response.End();
            }
        }

        public void GetCurrentUserDetail(HttpContext context)
        {
            string user = Controller.AD.LdapAuthentication.GetCurrentUser();
            string role = Controller.AD.LdapAuthentication.GetCurrentUserRole();
            string ip = context.Request.UserHostAddress;
            string complete = "{'User':'" + user + "','Role':'" + role + "','IP':'" + ip + "'}";
            context.Response.ContentType = "text/plain";
            context.Response.Write(JObject.Parse(complete));
        }

        public void SetCurrentUserDetail(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string saleUser = post["postData[username]"];
            Controller.AD.LdapAuthentication.SetCurrentRepresendto(saleUser);

            //string complete = "{'User':'" + user + "','Role':'" + role + "','IP':'" + ip + "'}";
            context.Response.ContentType = "text/plain";
            context.Response.Write(JObject.Parse("{Update:1}"));
        }

        public void GetSaleClientBySaleCo(HttpContext context)
        {
            string user = Controller.AD.LdapAuthentication.GetCurrentUser();
            string kk = Controller.Helper.SaleCo.GetSaleClientBySaleCo(user);
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }
        public void CheckADuser(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string user = post["postData[username]"];
            tblUser User = Controller.AD.LdapAuthentication.FindUser(user);
            if (User != null)
            {

                context.Response.ContentType = "text/plain";
                context.Response.Write(JsonConvert.SerializeObject(User));
            }
            else
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("");
            }
        }
        public void GetProductCate(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string isall = post["postData[isAll]"];
            string kk = string.Empty;
            if (string.IsNullOrEmpty(isall))
            {
                kk = ProductGrp.GetProductCate();
            }
            else
            {
                kk = ProductGrp.GetProductCate(true);
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);
        }

        public void GetProductHier(HttpContext context)
        {
            string kk = Controller.Helper.ProductGrp.GetAllProdHier();
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }
        public void GetAllApproverMapping(HttpContext context)
        {
            string kk = Controller.Helper.Approver.GetAllApproverSaleMapping();
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }
        public void GetAllSaleCoMapping(HttpContext context)
        {
            string kk = Controller.Helper.SaleCo.GetAllSaleCoSaleMapping();
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }

        public void getAllNdPrice(HttpContext context)
        {
            string kk = Controller.Helper.NDPrice.getAllNdPriceJson();
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);
        }

        public void getLastestNdPriceItemJson(HttpContext context)
        {
            string kk = Controller.Helper.NDPrice.getLastestNdPriceItemJson();
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);
        }

        public void ExportSaPfile(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string doc = post["postData[docIDs][]"];
            string[] docs = Regex.Split(doc, ",");
            //var docs = new List<string> {"SPU20125008"};
            string kk = Controller.Helper.Document.exportSAPfile(docs);

            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }

        public void ExportSaPNDfile(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string ndround = post["postData[ndround]"];
            int indRount = -1;
            if (!string.IsNullOrEmpty(ndround))
            {
                indRount = Convert.ToInt32(ndround);
            }
            string kk = Controller.Helper.Document.exportSAPNDfile(indRount);

            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }
        public void DeleteDocs(HttpContext context)
        {

            HttpRequest post = HttpContext.Current.Request;
            string doc = post["postData[docIDs][]"];
            string[] docs = Regex.Split(doc, ",");
            //var docs = new List<string> {"SPU20125008"};

            var ds = docs.Select(s => new tblDocument {DocID = s, IsDisable = true}).ToList();
            var dds = docs.Select(s => new tblDocumentDatail() {DocID = s, isDisable = true}).ToList();
            int kk = Controller.Helper.Document.DocumentAction(ds, EnumAction.Update);
            Controller.Helper.Document.DocumentDetailAction(dds, EnumAction.Update);
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);
        }

        public void ReNewPincode(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string pincode = post["postData[Pincode]"];

            int kk = Controller.Helper.Member.ReNewPincode(pincode);
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }

        public void VerifyPincode(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string pincode = post["postData[Pincode]"];

            int kk = Member.VerifyPincode(pincode);
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);

        }

        public void GetCustomerListByDocs(HttpContext context)
        {
            HttpRequest post = HttpContext.Current.Request;
            string postdata = post["postData[DocsID][]"];

            string[] data = postdata.Split(',');

            string kk = Document.getCustByDocsIDJson(data);
            context.Response.ContentType = "text/plain";
            context.Response.Write(kk);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
